package com.candy.config;

import com.candy.filter.LoginFilter;
import com.candy.service.MyUserDetailServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
public class SecurityConfig {
    private final MyUserDetailServiceImpl myUserDetailService;

    //构造注入自定义UserDetailService
    @Autowired
    public SecurityConfig(MyUserDetailServiceImpl myUserDetailService) {
        this.myUserDetailService = myUserDetailService;
    }
    //注入AuthenticationManager
    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration configuration) throws Exception {
        return configuration.getAuthenticationManager();
    }
    //注入过滤器
    @Bean
    public LoginFilter loginFilter(AuthenticationManager authenticationManager){
        LoginFilter loginFilter = new LoginFilter();
        //表单密码对应方法，如果不进行自定义就是默认password,其实这里不配置也行，因为默认就是password
        loginFilter.setPasswordParameter("password");
        //表单用户名对应方法，如果不进行自定义就是默认username
        loginFilter.setUsernameParameter("username");
        //登陆表单提交对应的方法
        loginFilter.setFilterProcessesUrl("/userLogin");
        loginFilter.setAuthenticationManager(authenticationManager);
        //登陆成功后的操作
        loginFilter.setAuthenticationSuccessHandler(new MyAuthenticationSucccessHandler());
        //登陆失败后的操作
        loginFilter.setAuthenticationFailureHandler(new MyAuthenticationFailureHandler());
        return loginFilter;
    }
    //配置添加自定义认证数据源，替换过滤器
    @Bean
    protected SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests()
                .anyRequest().authenticated()
                .and().formLogin()
                //登陆页面的路由
                .loginPage("/login")
                .permitAll()
                .and().logout()
                .logoutUrl("/logout").logoutSuccessUrl("/login").permitAll()
//        logoutSuccessHandler(new MyLogoutSuccessHandler())
                .and().userDetailsService(myUserDetailService)
                .csrf().disable();
        http.addFilterAt(loginFilter(http.getSharedObject(AuthenticationManager.class)), UsernamePasswordAuthenticationFilter.class);
//        配置403权限不足页面
        http.exceptionHandling().accessDeniedPage("/403");
        return http.build();
    }
}